package com.jf.apply_car.util;

import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginInfo = request.getSession().getAttribute(MyConstants.LOGIN_SESSION_KEY);
        if (loginInfo == null) {
            if ("XMLHttpRequest".equals(request.getHeader("x-requested-with"))) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(JSON.toJSON(ResultJson.error(401, "登录失效，请刷新页面！")));
            } else {
                response.sendRedirect(request.getContextPath() + "/nologin.jsp");
            }
            return false;
        }
        return true;
    }
}
